<style rel="stylesheet/scss" lang="scss" scoped>
</style>

<template>
    <div>
        <div class="container">
            <el-card shadow="hover" style="padding:0">

                <el-form ref="searchForm" :inline="true" :model="searchForm" size="medium" label-width="120px">
                    <el-card class="operate_container" shadow="never">
                        <div class="wrapper">

                            <!-- 关键字模糊检索 -->
                            <div class="searchKeyword">
                                <el-form-item prop="keyword">
                                    <el-input placeholder="请输入检索关键字" v-model="searchForm.keyword" clearable @clear="handleResetSearch('searchForm')">
                                        <el-button slot="append" icon="el-icon-search" @click="handleSearch()"></el-button>
                                    </el-input>
                                </el-form-item>
                            </div>

                            <!-- 操作按钮 -->
                            <div>
                                <el-button type="primary" icon="el-icon-plus" size="medium" circle @click="addOrUpdateVisible"></el-button>
                                <el-button type="danger" icon="el-icon-delete" size="medium" circle @click="handleDelete"></el-button>
                                <el-button type="primary" icon="el-icon-refresh" size="medium" circle @click="handleResetSearch('searchForm')"></el-button>
                            </div>
                        </div>
                    </el-card>
                </el-form>

                <!-- 表格 -->
                <el-table
                    ref="table" size="small" empty-text="暂无数据"
                    element-loading-text="给我一点时间"
                    fit stripe border highlight-current-row
                    v-loading="dataListLoading"
                    :data="dataList"
                    :header-cell-style="{'padding-top': '10px', 'height': '50px', 'color': '#515A6E', 'background-color': '#f8f8f9'}"
                    @selection-change="handleSelection">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column type="index" width="55" align="center"></el-table-column>

                    <el-table-column label="品牌LOGO" align="center" width="130">
                        <template slot-scope="scope">
                            <el-image style="width: 100px; height: 100px" :src="scope.row.logo" fit="contain"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column label="品牌名" prop="name" align="center"/>
                    <el-table-column label="介绍" prop="descript" align="center"/>
                    <el-table-column label="显示状态" prop="showStatus" align="center">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.showStatus"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="0"
                                @change="updateBrandStatus(scope.row)"
                            ></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="检索首字母" prop="firstLetter" align="center"/>
                    <el-table-column label="排序" prop="sort" align="center"/>
                    <el-table-column label="创建时间" prop="ctime" align="center"/>
                    <el-table-column label="最后更新时间" prop="utime" align="center"/>

                    <el-table-column label="操作" width="180px" align="center" fixed="right">
                        <template slot-scope="scope">
                            <div class="table_action">
                                <el-button type="text" size="small" @click="handleUpdateCatelog(scope.row.id)">关联分类</el-button>
                                <el-button type="primary" icon="el-icon-edit" circle size="small" @click="addOrUpdateVisible(scope.row)"></el-button>
                                <el-button type="danger" icon="el-icon-delete" circle size="small" @click="handleDelete(scope.row)"></el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页工具栏 -->
                <div class="pagination">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="searchForm.page"
                            :page-sizes="[10, 20, 30, 50, 100, 200]"
                            :page-size="searchForm.limit"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="totalPage">
                    </el-pagination>
                </div>

                <!-- 窗口 -->
                <el-dialog
                    :title="!form.id ? '新增' : '修改'"
                    :visible.sync="visible" :close-on-click-modal="false" @close="handleDialogClose">
                    <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                        <el-form-item label="品牌牌名" prop="name">
                            <el-input v-model="form.name" placeholder="品牌名" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="LOGO地址" prop="logo">
                            <single-upload v-model="form.logo"></single-upload>
                            <!-- <el-input v-model="form.logo" placeholder="品牌logo地址" style="width: 80%;"></el-input> -->
                        </el-form-item>
                        <el-form-item label="品牌介绍" prop="descript">
                            <el-input v-model="form.descript" placeholder="介绍" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="是否显示" prop="showStatus">
                            <el-radio-group v-model="form.showStatus">
                                <el-radio :label="1" border>显示</el-radio>
                                <el-radio :label="0" border>不显示</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="检索首字母" prop="firstLetter">
                            <el-input v-model="form.firstLetter" placeholder="检索首字母" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="排序" prop="sort">
                            <el-input-number v-model="form.sort" :min="1" :max="10000" placeholder="排序" style="width: 80%;"></el-input-number>
                        </el-form-item>
                        

                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button @click="visible = false">取 消</el-button>
                        <el-button @click="handleSubmit('form')" type="primary" :loading="submitLoading">提 交</el-button>
                    </div>
                </el-dialog>

                <el-dialog title="关联分类" :visible.sync="cateRelationDialogVisible" width="40%">
                    <el-popover placement="right-end" v-model="popCatelogSelectVisible" width="400">
                        <category-cascader :categoryPath.sync="categoryPath" styles="width: 100%;"></category-cascader>

                        <div style="text-align: right; margin-top: 10px">
                            <el-button size="mini" type="text" @click="popCatelogSelectVisible = false">取消</el-button>
                            <el-button type="primary" size="mini" @click="addCatelogSelect">确定</el-button>
                        </div>

                        <el-button slot="reference">新增关联</el-button>
                    </el-popover>
                    
                    <el-table :data="cateRelationTableData" style="width: 100%">
                        <el-table-column prop="id" label="#"></el-table-column>
                        <el-table-column prop="brandName" label="品牌名"></el-table-column>
                        <el-table-column prop="cateName" label="分类名"></el-table-column>
                        <el-table-column fixed="right" header-align="center" align="center" label="操作">
                        <template slot-scope="scope">
                            <el-button
                            type="text"
                            size="small"
                            @click="deleteCateRelationHandle(scope.row.id)"
                            >移除</el-button>
                        </template>
                        </el-table-column>
                    </el-table>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="cateRelationDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="cateRelationDialogVisible = false">确 定</el-button>
                    </span>
                </el-dialog>
            </el-card>
        </div>
    </div>
</template>

<script>
import { save, deleted, updated, info, list, page, selectMyPage } from "@/api/product/pmsbrand"
import CategoryCascader from '@/views/product/components/category-cascader'
import SingleUpload from '@/views/components/upload/single-upload'

export default {
    components: {
        CategoryCascader,
        SingleUpload
    },
    data() {
        return {
            visible: false,
            searchVisible: false,
            submitLoading: false,

            dataList: [],
            totalPage: 0,
            dataListLoading: true,
            selectionRows: [],

            searchForm: {
                page: 1,
                limit: 10,
                sortColumns: 'ctime,sort',
                sortType: 'desc',
                keyword: null,
                name: null
            },
            form: {
                id: null,
                name: null,
                logo: null,
                descript: null,
                showStatus: null,
                firstLetter: null,
                sort: null,
                ctime: null,
                utime: null
            },
            rules: {
                name: [
                    { required: true, message: '品牌名不能为空', trigger: 'blur' }
                ]
            },

            brandId: null,
            cateRelationDialogVisible: false,
            popCatelogSelectVisible: false,
            cateRelationTableData: [],
            categoryPath: []
        }
    },
    mounted() {
    	this.$nextTick(function () {
	        this.getDataList()
    	})
    },
    methods: {
        handleSelection(selection) { // 多选
            this.selectionRows = selection
        },
        handleSizeChange(val) { // 每页数量
            this.searchForm.limit = val
            this.getDataList()
        },
        handleCurrentChange(val) { // 页码
            this.searchForm.page = val
            this.getDataList()
        },
        handleResetSearch(name) { // 重置搜索表单
            this.handleReset(name)
            this.getDataList()
        },
        handleReset(name) { // 重置表单
            const refs = this.$refs
            refs[name].resetFields()
        },
        handleSearch() { // 单条件搜索
            this.getDataList()
        },
        handleDialogClose() { //表单窗口关闭
            this.handleReset('form')
        },

		/**
         * 打开表单窗口
         */
		addOrUpdateVisible(row) {
            this.visible = true
            if (row.id) {
                this.getInfo(row.id).then(res => {
                    this.form = Object.assign({}, res.data)
                })
            } else {
                this.form.id = null
            }
        },

		/**
         * 提交表单
         */
        handleSubmit(name) {
        	const refs = this.$refs
            refs[name].validate((valid) => {
                if (valid) {
                    this.submitLoading = true
                    if (!this.form.id) {
                        save(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else if (this.form.id) {
                        updated(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else {
                        console.log('未知操作');
                    }
                }
            })
        },
		
		/**
         * 删除
         */
        handleDelete(row) { 
            let ids = []
            if (row.id != undefined) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {    
                this.$confirm('确定要删除？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                    deleted(ids).then(res => {
                        if (this.ResultMessage(res)) {
                            this.getDataList()
                        } 
                    }).catch(error => {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    })
                }).catch(() => {})
            }
        },

		/**
         * 详细信息
         */
        getInfo(id) {
            if (id !== undefined) {
                return info(id).then(res => {
                    if (this.ResultMessage(res, false)) {
                        return res
                    } else {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    }
                }).catch(error => {
                    this.$notify({ title: '错误', message: error, type: 'error' });
                })
            }
        },
		
        /**
         * 数据列表
         */
        getDataList() {
            page(this.searchForm).then(res => {
                if (this.ResultMessage(res, false)) {
                    this.dataList = res.data.records
                    this.totalPage = res.data.total
                    this.dataListLoading = false
                } else {
                    this.dataListLoading = false
                }
            }).catch(error => {
                this.dataListLoading = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        },

        /**
         * 修改状态
         */
        updateBrandStatus(data) {
            let { id, showStatus } = data;
            updated({ id, showStatus }).then(res => {
                if (this.ResultMessage(res)) {
                    this.submitLoading = false
                    this.getDataList()
                } else {
                    this.submitLoading = false
                }
            }).catch(error => {
                this.submitLoading = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        },

        handleUpdateCatelog(brandId) {
            this.cateRelationDialogVisible = true;
            this.brandId = brandId;
            this.getCateRelation();
        },

        getCateRelation() {
            this.$http({
                url: '/product/pmscategorybrandrelation/category/list',
                method: "get",
                params: {
                    brandId: this.brandId
                }
            }).then(({ data }) => {
                this.cateRelationTableData = data;
            });
        },
        addCatelogSelect() {
            //{"brandId":1,"catelogId":2}
            this.popCatelogSelectVisible =false;
            this.$http({
                url: '/product/pmscategorybrandrelation/save',
                method: "post",
                data: {brandId: this.brandId, cateId: this.categoryPath[this.categoryPath.length-1]}
            }).then(({ data }) => {
                this.getCateRelation();
            });
        },
        deleteCateRelationHandle(id) {
            this.$http({
                url: '/product/pmscategorybrandrelation/delete',
                method: "post",
                data: [id]
            }).then(({ data }) => {
                this.getCateRelation();
            });
        },
    }
}
</script>